/*
 * SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

// 校验zip文件的完整性
use anyhow::Result;

use crate::cli::ZipArgs;
use crate::utils::common::{test_zip_with_command, test_zip_with_unzip};

pub fn execute(args: &ZipArgs) -> Result<()> {
    log::info!("Test mode enabled.");

    // 检查zip文件是否存在
    let zipfile = args
        .zipfile
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("No zip file specified for testing"))?;

    if !zipfile.exists() {
        return Err(anyhow::anyhow!(
            "zip file '{}' not found",
            zipfile.display()
        ));
    }

    if let Some(test_cmd) = &args.test.test_cmd {
        if let Err(e) = test_zip_with_command(test_cmd, zipfile) {
            println!("test of {} FAILED", zipfile.display());
            log::error!("test of {} FAILED: {}", zipfile.display(), e);
            return Err(e);
        }
    } else if let Err(e) = test_zip_with_unzip(zipfile, args.basic_options.verbose) {
        println!("test of {} FAILED", zipfile.display());
        log::error!("test of {} FAILED: {}", zipfile.display(), e);
        return Err(e);
    }
    println!("test of {} OK", zipfile.display());

    Ok(())
}

/// 执行zip文件测试，用于在压缩完成后调用
pub fn test_zip_file(args: &ZipArgs) -> Result<()> {
    execute(args)
}
